package com.swz.dcrm.ui.analyze;


import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.DataSet;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.BuildAndDefeatedCount;
import com.swz.dcrm.model.DeliveryAndCancleOrderCount;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;

import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.AnalyzeViewModel;
import com.swz.dcrm.util.DateUtils;
import com.swz.dcrm.util.Tool;
import com.swz.dcrm.widget.MyMarkerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class AnalyzeType5Fragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.line_chart)
    LineChart lineChart;
    @BindView(R.id.tv_date)
    TextView tvDate;
    private XAxis xAxis;                //X轴
    private YAxis leftYAxis;            //左侧Y轴
    private YAxis rightYaxis;           //右侧Y轴
    private Legend legend;

    private List<DeliveryAndCancleOrderCount> deliveryAndCancleOrderCounts;
    private TimePickerView timePickerView;
    private int type;
    private List<String>xList;



    @Inject
    AnalyzeViewModel analyzeViewModel;


    public static AnalyzeType5Fragment newInstance() {

        return new AnalyzeType5Fragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())){
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        lineChart.clear();
        Date date=DateUtils.dateParse(tvDate.getText().toString(),"yyyy年M月");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)+1);
        String start=DateUtils.dateFormat(date,"yyyy-MM");
        String end=DateUtils.dateFormat(calendar.getTime(),"yyyy-MM");

        if(type==1){
            analyzeViewModel.getAnalyzeType5(start,end)
                    .observe(this, listBaseResponse -> {
                        if(listBaseResponse==null){
                            return;
                        }
                        analyzeViewModel.getAnalyzeType5().removeObservers(this);
                        if(listBaseResponse.isSuccess()){

                            deliveryAndCancleOrderCounts=listBaseResponse.getData();
                            List<Integer> list=new ArrayList<>();
                            List<Integer> list1=new ArrayList<>();
                            xList=new ArrayList<>();

                            for (DeliveryAndCancleOrderCount deliveryAndCancleOrderCount:deliveryAndCancleOrderCounts){
                                list.add(deliveryAndCancleOrderCount.getDeliveryCarCount());
                                list1.add(deliveryAndCancleOrderCount.getCancelOrderCount());
                                xList.add(deliveryAndCancleOrderCount.getStatisticsTime());
                            }

                            showLineChart(list,"交车数",list1,"退订数");
                            initChart(lineChart);
                            MyMarkerView myMarkerView=new MyMarkerView(getContext(),xList);
                            myMarkerView.setChartView(lineChart);
                            lineChart.setMarker(myMarkerView);

                        }
                    });
        }else if(type==2){

            analyzeViewModel.getAnalyzeType4(start,end)
                    .observe(this,listBaseResponse -> {
                        if(listBaseResponse==null){
                            return;
                        }
                        analyzeViewModel.getAnalyzeType4().removeObservers(this);
                        if(listBaseResponse.isSuccess()){


                            List<Integer> list=new ArrayList<>();
                            List<Integer> list1=new ArrayList<>();
                            xList=new ArrayList<>();

                            for (BuildAndDefeatedCount buildAndDefeatedCount:listBaseResponse.getData()){
                                list.add(buildAndDefeatedCount.getCreateFileCount());
                                list1.add(buildAndDefeatedCount.getDefeatedCount());
                                xList.add(buildAndDefeatedCount.getStatisticsTime());
                            }
                            initChart(lineChart);
                            showLineChart(list,"新建档数",list1,"战败数");


                            MyMarkerView myMarkerView=new MyMarkerView(getContext(),xList);
                            myMarkerView.setChartView(lineChart);
                            lineChart.setMarker(myMarkerView);
                        }
                    });
        }


    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_analyze_type5;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        AnalyzeType5FragmentArgs analyzeType5FragmentArgs=AnalyzeType5FragmentArgs.fromBundle(getArguments());
        title.setText(analyzeType5FragmentArgs.getTitle());
        if(analyzeType5FragmentArgs.getTitle().equals(getString(R.string.analysis_type5))){
            type=1;
        }else if(analyzeType5FragmentArgs.getTitle().equals(getString(R.string.analysis_type4))){
            type=2;
        }
        lineChart.setBackgroundColor(getResources().getColor(R.color.white));
        lineChart.setDrawBorders(false);
        Description description = new Description();
//        description.setText("需要展示的内容");
        description.setEnabled(false);
        lineChart.setDescription(description);

        lineChart.getAxisRight().setEnabled(false);
        tvDate.setText(DateUtils.dateFormat(new Date(),"yyyy年MM月"));
        timePickerView=getTimePickerView((date, v) -> {
            tvDate.setText(DateUtils.dateFormat(date,"yyyy年MM月"));
            onLoadRetry();

        }).setType(new boolean[]{true, true, false, false, false, false}).build();
        return true;
    }
    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     * @param color       线条颜色
     * @param mode
     */
    private void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(3f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setDrawValues(false);
        lineDataSet.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.valueOf((int)value);
            }
        });



        //设置折线图填充
        lineDataSet.setDrawFilled(false);

        //lineDataSet.setFormLineWidth(1f);

        lineDataSet.setFormSize(15.f);
        if (mode == null) {
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        } else {
            lineDataSet.setMode(mode);
        }
    }
    /**
     * 展示曲线
     *
     * @param dataList 数据集合

     */
    public void showLineChart(List<Integer> dataList,String title,List<Integer> data1,String title1) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {


            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */

                Entry entry = new Entry(i,Float.valueOf(dataList.get(i)));
                entries.add(entry);


        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, title);
        initLineDataSet(lineDataSet, getResources().getColor(R.color.blue_0f6eff), LineDataSet.Mode.LINEAR);
        LineData lineData = new LineData(lineDataSet,getLine(data1,title1));
        lineChart.setData(lineData);


    }
    /**
     * 添加曲线
     */
    private LineDataSet getLine(List<Integer> dataList, String title) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {

            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */

            Entry entry = new Entry(i,dataList.get(i));

            entries.add(entry);

        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, title);
        lineDataSet.setLabel(title);

        initLineDataSet(lineDataSet, getResources().getColor(R.color.orange_ff8730), LineDataSet.Mode.LINEAR);
        return lineDataSet;


    }


    private void initChart(LineChart lineChart) {
        /***图表设置***/
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        //是否显示边界
        lineChart.setDrawBorders(false);
        //是否可以拖动
        lineChart.setDragEnabled(false);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置XY轴动画效果
        lineChart.animateY(0);
        lineChart.animateX(0);

        /***XY轴的设置***/
        xAxis = lineChart.getXAxis();
        xAxis.setDrawGridLines(false);
        leftYAxis = lineChart.getAxisLeft();
        leftYAxis.setDrawGridLines(true);
        rightYaxis = lineChart.getAxisRight();
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);

        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if(xList.size()<=value){
                    return "";
                }
                String date=DateUtils.dateFormat(xList.get((int)value),"MM-dd");
                return date;
            }
        });


        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
        rightYaxis.setAxisMinimum(0f);

        /***折线图例 标签 设置***/
        legend = lineChart.getLegend();
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setTextSize(12f);

        //显示位置 左上方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setYOffset(20);

        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);

    }


    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }
    @OnClick(R.id.tv_date)
    public void pickDate(){
        timePickerView.show();
    }

}
